package cn.zy.jboa.dao.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import cn.zy.jboa.dao.CommonDAO;
import cn.zy.jboa.entity.BizLeave;

@Repository("commonDAOImpl")
public class CommonDAOImpl extends HibernateDaoSupport implements CommonDAO {

	public CommonDAOImpl(){}
	@Autowired
	public CommonDAOImpl(@Qualifier("sessionFactory")SessionFactory sessionFactory){
		this.setSessionFactory(sessionFactory);
	}
	@Override
	public Object get(Class clazz, Serializable id) {
		Object ret = super.getHibernateTemplate().get(clazz, id);
		return ret;
	}

	@Override
	public Serializable add(Object obj) {
		Serializable ret = super.getHibernateTemplate().save(obj);
		return ret;
	}

	@Override
	public void del(Class clazz, Serializable id) {
		super.getHibernateTemplate().delete(this.get(clazz, id));
	}

	@Override
	public void update(Object obj) {
		getHibernateTemplate().clear();
		super.getHibernateTemplate().update(obj);
	}

	@Override
	public List search(String hql) {
		List ret = super.getHibernateTemplate().find(hql);
		return ret;
	}
	@Override
	public List query(final String hql,final int first,final int size) {
		return this.getHibernateTemplate().execute(
			new HibernateCallback<List>() {
				@Override
				public List doInHibernate(Session session)
						throws HibernateException, SQLException {
					return session.createQuery(hql).setFirstResult(first).setMaxResults(size).list();
				}
				
			});
	}
	@Override
	public Object count(final String hql) {
		return this.getHibernateTemplate().execute(
				new HibernateCallback<Object>() {
					@Override
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						return session.createQuery(hql).uniqueResult();
					}
					
				});
	}

}
